<template>
  <view class="main-login">
    <view class="title">登录</view>
    <form @submit="loginSubmit">
      <view class="input-info">
        <view class="inline-text">电话</view>
        <input class="inline-text" type="text" name="phone" v-model="phone" />
        <view class="inline-text">验证码</view>
        <view style="display: grid; grid-template-columns: 50% 50%">
          <input class="inline-text" type="text" name="autoCode" />
          <view>
            <button v-if="!cannotSendMessage" @click="sendMsgSubmit">
              发送验证码
            </button>
            <button v-else disabled="true">等待中 {{ second_remain }} s</button>
          </view>
        </view>
      </view>
      <button form-type="submit" type="primary">登录/注册</button>
    </form>
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      phone: "",
      // localData.status: "",
      cannotSendMessage: false,
      second_remain: 0,
    };
  },
  onLaunch: function () {
    uni.getStorage({
      key: "localData",
      success: (res) => {
        phone = res.data.phone;
      },
    });
  },
  computed: mapState(["hasLogin", "localData"]),
  methods: {
    countDown: function () {
      this.second_remain = 60;
      this.cannotSendMessage = true;
      let c0untD0wN = setInterval(() => {
        if (this.second_remain > 0) {
          this.cannotSendMessage = true;
          this.second_remain--;
        } else {
          clearInterval(c0untD0wN);
          this.cannotSendMessage = false;
        }
      }, 1000);
    },
    sendMsgSubmit: function () {
      this.countDown();
      // console.log(this.phone);
      if (this.phone.length !== 11) {
        uni.showToast({ title: "请输入有效的手机号", icon: "error" });
        return;
      }
      uni.showLoading({ title: "加载中" });
      let postData = {
        option: "sendMessage",
        phone: this.phone,
      };
      console.log("sendmsg", postData);
      this.$http
        .post(this.urlApi.user, postData)
        .then((res) => {
          console.log(res.data);
          uni.hideLoading();
          let status = res.data.status;
          this.localData.status = status;
          switch (status) {
            case "100": {
              uni.showToast({ title: "老用户 短信发送成功" });
              break;
            }
            case "101": {
              uni.showToast({ title: "老用户 短信发送失败", icon: "error" });
              break;
            }
            case "200": {
              uni.showToast({ title: "新用户 短信发送成功" });
              break;
            }
            case "201": {
              uni.showToast({ title: "新用户 短信发送失败", icon: "error" });
              break;
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({ title: "请求失败", icon: "error" });
          console.log(err);
        });
    },
    loginSubmit: function (e) {
      // console.log(e);
      let values = e.detail.value;
      let postData = {
        phone: values.phone,
        autoCode: values.autoCode,
        option: "checkAutoCode",
      };
      // this.localData.status = "100"; // for debug

      switch (this.localData.status) {
        case "100": {
          postData.type = "signIn";
          break;
        }
        case "200": {
          postData.type = "signUp";
          break;
        }
        default: {
          uni.showToast({ title: "请重新验证", icon: "error" });
          return;
        }
      }
      console.log("login postData", postData);
      this.$http
        .post(this.urlApi.user, postData)
        .then((res) => {
          let status = res.data.status;
          console.log("login res", res.data);
          switch (status) {
            case "100": {
              let saveData = {
                phone: values.phone,
                nickname: res.data.user_name,
                sex: res.data.user_sex,
                description: res.data.user_description,
              };
              console.log("saveData", saveData);
              this.login(saveData);
              uni.showToast({ title: "验证成功", icon: "success" });
              setTimeout(() => {
                uni.switchTab({ url: "/pages/userMain/mySpace/mySpace" });
              }, 1000);
              break;
            }
            case "101": {
              let saveData = {
                phone: values.phone,
                nickname: res.data.user_name,
                sex: res.data.user_sex,
                description: res.data.user_description,
              };
              console.log("saveData", saveData);
              this.login(saveData);
              uni.showToast({ title: "注册成功", icon: "success" });
              break;
            }
          }
        })
        .catch((err) => {
          uni.showToast({ title: "请求出错", icon: "error" });
          console.log(err);
        });
    },
    randomChars: function (len) {
      len = len || 6;
      var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      var maxPos = $chars.length;
      var pwd = "";
      for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    /*signupOnClick: function () {
      uni.navigateTo({ url: "/pages/login/signUp" });
    },
    httpLoginSubmit: function (e) {
      uni.showLoading({
        title: "登陆中...",
      });
      let userID = e.detail.value.userID,
        password = e.detail.value.password;
      if (userID == "" || password == "") {
        uni.hideLoading();
        uni.showToast({ title: "请输入正确的账号和密码!", icon: "error" });
      }
      this.$http
        .post(this.urlApi.user, {
          userID: userID,
          password: password,
          type: "authenticateByPassword",
          option: "signIn",
        })
        .then((res) => {
          uni.hideLoading();
          let status = res.data.status;
          // console.log("login", res.data);
          switch (status) {
            case this.$responseCode.login.loginSuccess: {
              this.login(res.data);
              uni.showToast({ title: "登录成功", icon: "success" });
              uni.switchTab({ url: "/pages/userMain/mySpace/mySpace" });
              break;
            }
            case this.$responseCode.login.userIdError: {
              uni.showToast({ title: "账号错误", icon: "error" });
              break;
            }
            case this.$responseCode.login.pwError: {
              uni.showToast({ title: "密码错误", icon: "error" });
              break;
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          this.response_data = err.data;
        });
    },*/
    ...mapMutations(["login"]),
  },
};
</script>

<style>
.input-info {
  margin: 0 auto;
  width: 90%;
  display: grid;
  grid-template-rows: 50% 50%;
  grid-template-columns: 25% 75%;
}
.inline-text {
  font-size: 0.8em;
  padding: 5px;
  margin: 5px;
  overflow: hidden;
  white-space: nowrap;
}

uni-input {
  border: grey 1px solid;
  border-radius: 5px;
  font-size: 1em;
}

.title {
  text-align: center;
  font-size: 2em;
}

uni-button {
  font-size: 0.8em;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
}

.response-data {
  font-size: 50%;
}
</style>